<template>
  <div class="editor-wrapper">
    <div id="editor"></div>
  </div>
</template>

<script>
import WangEditor from "wangeditor";
import { getToken } from "@/utils/auth";

export default {
  props: {
    value: {
      props: {
        type: String,
        default: ""
      }
    }
  },
  data() {
    return {
      instance: null
    };
  },
  watch: {
    value() {
      if (this.instance.txt.html() === this.value) {
        return;
      }
      this.instance.txt.html(this.value);
    }
  },
  mounted() {
    this.instance = new WangEditor(document.getElementById("editor"));
    Object.assign(this.instance.config, {
      uploadImgServer:
        "https://admin.xmzhuchen.com/api/base/upload?phone=" + getToken(),
      uploadFileName: "file",
      onchange: () => {
        this.$emit("input", this.instance.txt.html());
      },
      uploadImgHooks: {
        customInsert: (insertImgFn, result) => {
          insertImgFn("https://admin.xmzhuchen.com/" + result.data.file.url);
        },
        error() {}
      }
    });

    this.instance.create();
    this.instance.txt.html(this.value);
  },
  beforeDestroy() {
    this.instance.destroy();
    this.instance = null;
  }
};
</script>

<style lang="less" scoped>
.editor-wrapper {
  position: relative;
  z-index: 10;
}
</style>
